import {
	ref
} from 'vue'
// 列表hooks
export const usePaginatedList = (fetchFunction, initialQuery) => {
	const list = ref([])
	const pageNum = ref(1)
	const pagesize = ref(initialQuery.pagesize || 10)
	const noMoreData = ref(false)
	const loading = ref(false)
	const status = ref('more')
	status.value = 'loading'
	const fetchList = (isRefresh = false) => {
		//uni.showLoading()
		if (isRefresh) {
			pageNum.value = 1
			list.value = []
			noMoreData.value = false
			status.value = 'loading'
		} else {
			status.value = 'loading'
		}
		loading.value = true
		let query = {
			...initialQuery,
			'pageNum': pageNum.value,
			'pagesize': pagesize.value
		}
		fetchFunction(query).then(res => {
			console.log(res.length, 'vres')
			//uni.hideLoading()
			uni.stopPullDownRefresh()
			loading.value = false
			if (res.length == 0 || (res.data.length < pagesize.value)) {
				noMoreData.value = true
				status.value = 'noMore'
			} else {
				status.value = 'more'
			}
			if (isRefresh) {
				list.value = res.data || res
			} else {
				list.value = [...list.value, ...res.data]
			}
			pageNum.value++
		}).catch(() => {
			loading.value = false
			// uni.hideLoading()
			uni.stopPullDownRefresh()
			status.value = 'loading'
		})
	}
	const reachBottom = () => {
		if (!noMoreData.value && !loading.value) {
			fetchList()
		}
	}
	const onPullDown = () => {
		fetchList(true)
	}
	return {
		list,
		loading,
		noMoreData,
		fetchList,
		reachBottom,
		onPullDown,
		status
	}
}
